<template>
  <div id="vxePulldownMultiSelection">
    <vxe-pulldown :ref="'xDown44' + childIndex" transfer span="24" style="width: 100%">
      <template #default>
        <vxe-input class="enterNextInputFlag" v-model="keyvalue" autocomplete="off" auto-complete="new-password" :disabled="caUse" style="width: 100%" suffix-icon="vxe-icon-search" placeholder="请选择" @keydown.enter.stop="enterConfirmEvent()" @focus="focusEvent4" @blur="blurEvent4" @change="inputChange" @suffix-click="suffixClick4" @clear="clearConfirmEvent" clearable></vxe-input>
      </template>
      <template #dropdown>
        <el-container class="bg-gray solid" style="height: 350px">
          <!-- 最左侧选中显示 -->
          <el-aside width="220px">
            <div class="valueBox" style="max-height: 100%; overflow-y: auto; margin-top: 0.25em">
              <div class="flex justify-start valueItem" v-for="(itm, idx) in selectTableList" :key="idx">
                <div>
                  <span>
                    <vxe-button status="danger" type="text" class-name="text-red" icon="vxe-icon-delete" @click="deleteSelectedItem(idx)"></vxe-button>
                  </span>
                  <span class="margin-left-xs">
                    {{ idx + 1 + '、' + GetDisplayText(itm) }}
                    <!--  -->
                  </span>
                </div>
              </div>
            </div>
          </el-aside>
          <!-- 中间筛选条件 -->
          <el-aside width="240px" v-if="isQuickTable">
            <vxe-grid :ref="'quickTable' + childIndex" :auto-resize="false" border show-overflow height="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{
                isArrow: true,
                isEnter: true
              }" :column-config="{ resizable: true }" :loading="Qloading" :pager-config="{
                layouts: ['PrevPage', 'Jump', 'PageCount', 'NextPage'],
                ...tablePageQ
              }" :data="quickList" :columns="quickColumn" @cell-click="cellClickQuick" @page-change="pageChangeQuick"></vxe-grid>
          </el-aside>
          <el-main>
            <vxe-toolbar v-if="props.searchDisabled">
              <template #buttons>
                查询条件：
                <vxe-input v-model="form.searchValue" @keyup="enterHandlerFindList" @clear="findList(true)" style="width: calc(100% - 70px - 70px)" clearable></vxe-input>
                <vxe-button mode="text" status="primary" content="确定" @click="closeVxePullDownMultiSelection"></vxe-button>
              </template>
            </vxe-toolbar>
            <vxe-toolbar v-else>
              <template #buttons>
                <vxe-button mode="text" status="primary" content="确定" @click="closeVxePullDownMultiSelection" style="margin-left: 350px"></vxe-button>
              </template>
            </vxe-toolbar>
            <div class="my-dropdown4">
              <vxe-grid :ref="'gridTable4' + childIndex" :auto-resize="false" border show-overflow height="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{
                  isArrow: true,
                  isEnter: true,
                  editMethodExmItem4
                }" :edit-config="{ mode: 'row' }" :column-config="{ resizable: true }" :loading="loading" :pager-config="tablePage4" :data="tableList" :columns="tableColumn" @cell-click="cellClickEvent4" @page-change="pageChangeEvent4"></vxe-grid>
            </div>
          </el-main>
        </el-container>
      </template>
    </vxe-pulldown>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { pageSizes, IsEmpty, newGuid } from '@/utils/common';
let { proxy }: any = getCurrentInstance();
let props = defineProps({
  qUrl: String, //过滤条件数据请求地址
  url: String, //数据请求地址
  quickColumn: {}, //过滤条件列集合
  tableColumn: {}, //列集合
  displayTexts: {}, //显示字段集合
  displayTextObj: {}, //显示字段集合
  quickFilterObj: {}, //快速查询关键字段 [{searchKey:value,selectKey:value}]
  dataObj: {}, //接口参数。{key1:value1,key2:value2...}
  isDisabled: Boolean, //对外暴露的input是否可用
  isChild: Boolean, //是否子行(未用到)
  childIndex: String || Number, //组件传过来的类型(区分是哪个在用此组件)
  aimKeys: {}, //目标字段[{ targetField: value, sourceField: value }]
  resItem: String, //返回数据中，包含所需数据的名称
  isChangeName: Boolean, //输入框内容是否可手动更改
  compName: String, //组件名称(未用到)
  resIsArr: { Boolean, default: false }, //组件名称
  dicValues: Array as () => String[], //集合数组
  includeVal: {}, //点击列表选择时，通过includeVal判断是否已存在
  isQuickTable: Boolean, //是否有过滤条件列表
  eqValue: String, /**比较值 */
  searchDisabled:{ Boolean, default: true } //查询是否显示(默认显示)
}) as any;

defineExpose({
  clearConfirmEvent
});

let caUse = false;
let compId = newGuid();
let keyvalue = ref('');
let pageSizeList = pageSizes;
let pageSize = ref(200);
let pageIndex = ref(1);
let tablePage4 = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 200
});
let tablePageQ = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 20
});
let totalCount = ref(0);
let Qloading = ref(false); //中间筛选表格状态
let loading = ref(false);

let selectedItem = reactive({
  id: null,
  name: ''
});
// 组件右侧根据关键字查询
let form = reactive({
  searchValue: ''
});
let quickList = reactive([]);

let currentQuick = reactive({});
//绑定组织模块列表的数据
let tableList = reactive([]);

let selectTableList = reactive([]);

watch(
  () => props.displayTextObj,
  (nVal, oldvbal) => {
    keyvalue.value = nVal;
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.isDisabled,
  (nVal, oldvbal) => {
    if (nVal && typeof nVal === 'object') {
      selectTableList = nVal;
    }
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.isQuickTable,
  (nVal, oldvbal) => {
    if (nVal) {
      getQuickList();
    }
  },
  {
    deep: true,
    immediate: true
  }
);

// #region 【过滤条件】
function getQuickList() {
  Qloading.value = true;
  if (IsEmpty(props.qUrl)) {
    quickList = [];
    tableList = [];
    return;
  }
  const data: any = {
    sorting: null,
    skipCount: (tablePageQ.currentPage - 1) * tablePageQ.pageSize,
    maxResultCount: tablePageQ.pageSize
  };
  proxy.$http
    .get(proxy.qUrl, { params: data })
    .then((res: any) => {
      quickList = res.data;
      tablePageQ.total = IsEmpty(res.data.length) ? 1 : res.data.length;
      cellClickQuick({ row: res.data[0] });
      Qloading.value = false;
    })
    .catch((err) => {
      Qloading.value = false;
    });
}
function cellClickQuick({ row }) {
  if (IsEmpty(row)) {
    currentQuick = {} as any;
    quickList = [];
    tableList = [];
    return;
  }
  currentQuick = row;
  proxy.$nextTick(() => {
    const $XMidTable = proxy.$refs['quickTable' + props.childIndex];
    if ($XMidTable) {
      (proxy.$refs['quickTable' + props.childIndex] as any).setCurrentRow(row);
    }
  });
  findList();
}

// 过滤条件分页
function pageChangeQuick({ type, currentPage, pageSize }) {
  tablePageQ.currentPage = currentPage;
  tablePageQ.pageSize = pageSize;
  getQuickList();
}

// #endregion
//获取组织模块列表 isSelfInput:是否为来自本组件中的查询
function findList(isSelfInput = false) {
  loading.value = true;
  //#region  判断请求接口地址为空
  if (IsEmpty(props.url)) {
    loading.value = false;
    tableList = [];
    return;
  }
  //#endregion
  const filter = isSelfInput ? form.searchValue : selectedItem.name;
  const url = props.url;
  const data: any = {
    // searchValue //分析系统查找项目
    keyWords: IsEmpty(filter) ? null : filter.toString().trim().toUpperCase(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
    //inputCode:IsEmpty(this.selectedItem.name) ? null : this.selectedItem.name.toString().trim().toUpperCase(),
  };
  // 循环父组件传来的特殊查询字段，添加到data上
  if (!IsEmpty(props.dataObj)) {
    for (const key in props.dataObj) {
      if (props.dataObj[key]) {
        data[key] = props.dataObj[key];
      }
    }
  }
  // 循环查询条件传递的特殊查询字段
  if (props.isQuickTable && !IsEmpty(props.quickFilterObj)) {
    props.quickFilterObj.forEach((item) => {
      data[item.searchKey] = currentQuick[item.selectKey];
    });
  }

  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      // tableList = props.resIsArr ? res : IsEmpty(props.resItem) ? res.items : res[props.resItem];
      if (props.childIndex == 'dep' || props.childIndex == 'reqWard') {
        tableList = res.data.deptList;
        tablePage4.total = IsEmpty(res.data.deptList.length) ? 1 : res.data.deptList.length;
        // || props.childIndex == 'rptGroup'
      } else if (props.childIndex == 'instr') {
        tableList = res.data.records;
        tablePage4.total = IsEmpty(res.data.records.length) ? 1 : res.data.records.length;
      } else {
        tableList = res.data;
        tablePage4.total = IsEmpty(res.data.length) ? 1 : res.data.length;
      }

      if (props.dicValues && props.dicValues.length > 0 && props.eqValue !== undefined) {
        props.dicValues.forEach((e) => {
          const a = tableList.find((p) => p.id === e || p[props.eqValue] === e);
          selectTableList.push(a);
        });
      }

      // $forceUpdate();
      loading.value = false;
      proxy.$nextTick(() => {
        const $xTable = proxy.$refs['gridTable4' + props.childIndex] as any;
        // $xTable.focus();
        if (tableList.length > 0 && $xTable) {
          $xTable.setCurrentRow(tableList[0]);
        }
      });
    })
    .catch((err) => {
      loading.value = false;
      proxy.$alert(err, '提示');
    });
}

//获取列表
function findListWithUrl(qUrl: string) {
  if (IsEmpty(qUrl)) {
    tableList = [];
    return;
  }
  //#region  判断请求接口地址为空
  if (IsEmpty(props.url)) {
    loading.value = false;
    tableList = [];
    return;
  }
  //#endregion

  const url = qUrl;
  const data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      tableList = res.items;
      tablePage4.total = res.totalCount;
      // $forceUpdate();
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      proxy.$alert(err.data.error.message, '提示');
    });
}
//获取焦点
function focusEvent4() {
  if (props.isQuickTable) {
    getQuickList();
  } else {
    findList();
  }
  const $xTable = proxy.$refs['xDown44' + props.childIndex] as any;
  $xTable.showPanel();
}
// 失去焦点
function blurEvent4({ value }) {
  // 输入框内容未改变
  if (value === props.displayTextObj) {
    return;
  }
  if (props.isChangeName) {
    proxy.$emit('changeName', value);
  }
}
// 值改变
function inputChange({ value }) {
  selectedItem.name = value;
  findList();
}
function keyupEvent4() {
  const $xTable = proxy.$refs['xDown44' + props.childIndex] as any;
  $xTable.showPanel();
}
function suffixClick4() {
  const $xTable = proxy.$refs['xDown44' + props.childIndex] as any;
  $xTable.togglePanel();
}

//行选中
function cellClickEvent4({ row }) {
  const $xTable = proxy.$refs['xDown44' + props.childIndex] as any;
  //$xTable.hidePanel();
  if (IsEmpty(row)) {
    return;
  }
  // this.keyvalue = '';
  // props.displayTexts.forEach(element => {
  //   const keyArr = element.split('.');
  //   if (keyArr.length > 1) {
  //     let res = null;
  //     let data = row;
  //     keyArr.forEach((key, index) => {
  //       if (index > 0) {
  //         data = res;
  //       }
  //       res = data[key];

  //       if (index === keyArr.length - 1) {
  //         this.keyvalue += res + ' ';
  //       }
  //     });
  //   } else {
  //     this.keyvalue += row[element] + ' ';
  //   }
  // });
  if (selectTableList) {
    let ishas = false;
    for (const iterator of selectTableList) {
      const val = IsEmpty(props.includeVal) ? 'optionId' : props.includeVal;
      if (iterator[val] === row[val]) {
        ishas = true;
      }
    }
    if (!ishas) {
      selectTableList.push(row);
    }
  }
  proxy.$emit('confirmClick', {
    childIndex: props.childIndex,
    arr: selectTableList,
    aimKeys: props.aimKeys
  });
  proxy.$emit('confirmClick1', {
    childIndex: props.childIndex,
    arr: selectTableList,
    aimKeys: props.aimKeys
  });
}
function pageChangeEvent4({ type, currentPage, pageSize }) {
  tablePage4.currentPage = currentPage;
  tablePage4.pageSize = pageSize;
  findList();
  //todo
}
// 选中列表第一行
function selectRow() {
  (proxy.$refs.table as any).setCurrentRow(tableList[0]);
}
//回车选中
function enterConfirmEvent() {
  const $xTable = proxy.$refs['xDown44' + props.childIndex] as any;  
  if ($xTable.visiblePanel) {
    const gridTable = proxy.$refs['gridTable4' + props.childIndex] as any;
    const rowSelect = gridTable.getCurrentRecord();
    cellClickEvent4({ row: rowSelect });
  }
}
function editMethodExmItem4() {
  //todo
}
//删除选中
function deleteSelectedItem(rowidx) {
  selectTableList.splice(rowidx, 1);
  proxy.$emit('confirmClick', {
    childIndex: props.childIndex,
    arr: selectTableList,
    aimKeys: props.aimKeys
  });
}
// 清空
function clearConfirmEvent({ value }) {
  selectTableList.length = 0;
  proxy.$emit('confirmClick', {
    childIndex: props.childIndex,
    arr: [],
    aimKeys: props.aimKeys
  });
}

//拼接左侧显示文本
function GetDisplayText(itm) {
  if (IsEmpty(itm) || props.displayTexts.length === 0) {
    return;
  }
  let txt = '';

  props.displayTexts.forEach((key) => {
    const valArr = [];
    let value = itm[key];
    if (key.indexOf('.') > -1) {
      const keyArr = key.split('.');
      keyArr.forEach((val, index) => {
        if (index === 0) {
          valArr.push(itm[val]);
        } else {
          valArr.push(valArr[index - 1][val]);
        }
      });
      value = valArr[valArr.length - 1];
    }
    txt += value + ' ';
  });
  return txt;
}

// 回车查询
function enterHandlerFindList(e) {
  if (e.$event.code == 'Enter') {
    findList(true);
  }
}

// 确定按钮 关闭弹框
function closeVxePullDownMultiSelection() {
  // 获取VxePulldown实例
  const pulldownRef = proxy.$refs['xDown44' + props.childIndex];
  if (pulldownRef) {
    // 调用VxePulldown的隐藏方法
    pulldownRef.hidePanel();
  }
}


//初始化 走遍接口 返回第一条数据
function requireApiGetFirstData() {}
</script>
<style lang="scss" scoped>
#vxePulldownMultiSelection {
  // 选中列表颜色
  .el-table__body tr.current-row {
    > td {
      background-color: $brand-color;
      color: rgb(218, 218, 158);
    }
    .el-button--text {
      color: rgb(218, 218, 158);
    }
  }
}
.el-container {
  .el-main {
    padding: 0;
  }
}
.my-dropdown4 {
  padding: 2px;
  min-width: 400px;
  max-width: 600px;
  height: 308px;
  background-color: #fff;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}
:deep(.vxe-pager.size--mini) {
  height: 33px !important;
}
.valueBox {
  margin: 0;
}
.valueBox .valueItem {
  padding: 0.05em;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  cursor: pointer;
}
.valueBox .valueItem:not(:first-child) {
  margin-top: 0.25em;
}
</style>
